<template>
  <div class="container">
    <el-container>
      <el-header class="flex-row align-center">
        <header-con></header-con>
      </el-header>
      <el-container>
        <el-aside>
          <left-nav></left-nav>
        </el-aside>
        <el-main>
          <main-tabs></main-tabs>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import leftNav from "@/components/leftNav.vue";
import mainTabs from "@/components/mainTabs.vue";
import headerCon from "@/components/headerCon.vue";
import UserApi from "@/api/UserApi";
import { mapMutations, mapState, mapActions } from "vuex";

export default {
  components: {
    leftNav,
    mainTabs,
    headerCon,
  },
  computed: {
    ...mapState("webSocket", ["ws"]),
  },
  created() {
    this.init();
    let token = sessionStorage.getItem("Token");
    if (token != null) {
      UserApi.getUserInfo().then((res) => {
        console.log(res);
        this.SET_USERINFO(res.data);
      });
    }
  },
  mounted() {
    // 连接socket服务器
    this.startWebSocket();

    // 浏览器刷新前关闭连接
    const store = this;
    window.addEventListener("beforeunload", function (event) {
      store.clearWebSocket();
    });
  },
  watch: {
    ws(newVal) {
      if (newVal)
        this.ws.onmessage = (event) => {
          // 处理接收到的消息
          switch (event.data) {
            case "getOrders":
              this.$notify({
                type: "success",
                title: "新消息",
                message: "新订单",
                position: "top-right",
                duration: 3000,
                showClose: true,
                onClick: () => {
                  this.$router.push("/order");
                },
              });
              var utterThis = new window.SpeechSynthesisUtterance(
                "你有新的订单"
              );
              window.speechSynthesis.speak(utterThis)
              this.getCurrentOrders()
              break;
            default:
              break;
          }
        };
    },
  },
  methods: {
    ...mapActions("category", ["init"]),
    ...mapMutations("user", ["SET_USERINFO"]),
    ...mapActions("webSocket", ["startWebSocket", "clearWebSocket"]),
    ...mapActions("orders", ["getCurrentOrders"]),

  },
};
</script>

<style scoped>
.container {
  height: 100%;
}
.el-container {
  height: 100%;
  width: 100%;
}
.el-header {
  background-color: var(--header-bg);
}
.el-aside {
  width: fit-content !important;
}
.el-main {
  height: 100%;
  padding: 0 10px !important;
}
</style>